package com.lipi.mall.ware.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.lipi.common.utils.R;
import com.lipi.mall.ware.feign.MemberFeignService;
import com.lipi.mall.ware.vo.FareVO;
import com.lipi.mall.ware.vo.MemberAddressVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lipi.common.utils.PageUtils;
import com.lipi.common.utils.Query;

import com.lipi.mall.ware.dao.WareInfoDao;
import com.lipi.mall.ware.entity.WareInfoEntity;
import com.lipi.mall.ware.service.WareInfoService;


@Service("wareInfoService")
public class WareInfoServiceImpl extends ServiceImpl<WareInfoDao, WareInfoEntity> implements WareInfoService {

    @Autowired
    private MemberFeignService memberFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key)
                        .or().like("name", key)
                        .or().like("address", key)
                        .or().like("areacode", key);
            });
        }

        IPage<WareInfoEntity> page = this.page(
                new Query<WareInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }


    @Override
    public FareVO getFare(Long addrId) {

        FareVO fareVo=new FareVO();

        R r = memberFeignService.info(addrId);
        MemberAddressVO entity = r.get("memberReceiveAddress",new TypeReference<MemberAddressVO>() {
        });

        //运费计算
        //todo 运费应该接入物流系统根据物流费用计算,此处简略处理
        if (entity != null) {
            String phone = entity.getPhone();
            String fare = phone.substring(phone.length() - 1, phone.length());

            fareVo.setFare(new BigDecimal(fare));
            fareVo.setAddress(entity);

            return fareVo;
        }
        return null;
    }

}